import { router,addRoutes } from "@/router"
// import { getToken } from "@/utils/auth"
import { toast,showFullLoading,hideFullLoading } from "@/utils/toast"
// import store from "./store"
import { useUserStore } from "@/stores/user"
import { usePageStore } from "@/stores/page"
// 全局前置守卫
let hasGetInfo = false
router.beforeEach(async (to,from,next)=>{
    // 只要路由发生变化，页面顶部有进度条
    showFullLoading()
    const userStore = useUserStore()
    const token = userStore.token
    // console.log('我是permission.js',token,to.path)
    // 没有登录，强制跳转回登录页
    if(!token && to.path != "/login" ){
        if(to.path == "/register"){
            return next()
        }
        toast("请先登录","error")
        return next({ path:"/login" })
    }

    // 防止重复登录
    if(token && to.path == "/login"){
        // console.log(`我是to:${JSON.stringify(to)}`)
        // console.log(`我是from:${JSON.stringify(from)}`)
        // console.log(`我是next:${next}`)
        toast("请勿重复登录","error")
        return next({ path:from.path ? from.path : "/" })
    }

    // 如果用户登录了，调用全局变量里的方法，将token存储在vuex当中
    let hasNewRoutes = false
    if(token && !hasGetInfo){
        const pageStore = usePageStore()
        const userStore = useUserStore()
        const uid = userStore.user[0].id
        let { menus } = await pageStore.getInfo(uid)
        // let { menus } = await store.dispatch("getinfo")
        // 防止多次请求getinfo
        hasGetInfo = true
        // 动态添加路由
        hasNewRoutes = addRoutes(menus)
    }
    // 设置页面标题
    let title = (to.meta.title ? to.meta.title : "") + "-zd后台"
    document.title = title

    // next()
    hasNewRoutes ? next(to.fullPath) : next() // 循环path,防止重新刷新404
})

// 全局后置守卫
router.afterEach((to, from) => hideFullLoading())